package com.siemens.industrial.web.mvc.controller.admin;

import com.siemens.industrial.model.JobType;
import com.siemens.industrial.model.admin.Service;
import com.siemens.industrial.model.admin.SystemConfig;
import com.siemens.industrial.model.admin.Tenant;
import com.siemens.industrial.model.admin.User;
import com.siemens.industrial.utils.*;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.ServeService;
import com.siemens.industrial.web.mvc.service.admin.SystemConfigService;
import com.siemens.industrial.web.mvc.service.admin.TenantService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qupen on 2016/9/1.
 */
@Controller
public class TenantController {
    @Resource
    TenantService tenantService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    ServeService serveService;

    @Resource
    AuthService authService;

    @Resource
    SystemConfigService systemConfigService;

    @Resource
    WriteLogs writeLogs;

    @RequestMapping(value = "/admin/tenant/create", method = RequestMethod.GET)
    public String getCreateTenantPage(HttpServletRequest request, ModelMap modelMap) {
        List<Service> services = serveService.getServiceList();
        String url = request.getHeaders("host").nextElement();
        modelMap.put("serviceList", services);
        modelMap.put("url", url);
        return "admin/createTenant";
    }

    @RequestMapping(value = "/admin/api/v1/tenant/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createTenant(@RequestBody Map<String, Object> o) {
        try {
            String password = PasswordUtil.get(8);
            boolean b = tenantService.save(o, passwordEncoder.encode(password));
            if (b) {
                String userId = ((User) authService.currentUser()).getUserId();
                String info = "{\"currentUser\":\"" + userId + "\",\"key\":\"" + o.get("key").toString() + "\",\"type\":\"createTenant\"}";
                SocketClient socketClient = new SocketClient();
                socketClient.sendMessage(JobType.Event.toString(), info);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                User currentUser = (User) authService.currentUser();
                Tenant tenant = tenantService.getTenantByKey(o.get("key").toString());
                String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "创建了租户\"" + tenant.getTenantName() + "\"。";
                writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
            }
            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
//            return systemConfigService.sendMail(o.get("mail").toString(),"账户初始密码推送","您的初始密码为："+password);
        } catch (SiemensException e) {
            e.printStackTrace();
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/admin/tenant/list", method = RequestMethod.GET)
    public String getTenantListPage() {
        return "admin/tenant_list";
    }

    @RequestMapping(value = "/admin/tenant/update", method = RequestMethod.GET)
    public String getUpdateUserPage(@RequestParam(name = "id") String tenantId, ModelMap modelMap, HttpServletRequest request) {
        Tenant tenant = tenantService.getTenant(tenantId);
        String url = request.getHeaders("host").nextElement();
        modelMap.put("tenant", tenant);
        modelMap.put("url", url);
        return "admin/updateTenant";
    }

    @RequestMapping(value = "/admin/api/v1/tenant/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTenantList() {
        List<Tenant> tenants = tenantService.getTenantList();

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(tenants).build();
    }

    @RequestMapping(value = "/admin/api/v1/tenant/initPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> initTenantPassword(@RequestBody Map<String, Object> data) {
        String password = PasswordUtil.get(8);
        String tenantId = data.get("tenantId").toString();
        try {
            int i = tenantService.resetPassword(passwordEncoder.encode(password), tenantId);
            if (i == 1) {
                Tenant tenant = tenantService.getTenant(tenantId);
                if (tenant != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    User currentUser = (User) authService.currentUser();
                    String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "重置了租户\"" + tenant.getTenantName() + "\"的密码。";
                    writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
                    return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
//                    String email = tenant.getManagerEmail();
//                    return systemConfigService.sendMail(email,"重置密码","新密码为："+password);
                }
            }
        } catch (SiemensException e) {
            e.printStackTrace();
        }

        return RestResponse.create(GlobalResponseCode.ERROR_RESET_PASSWORD_FAIL).build();
    }

    @RequestMapping(value = "/admin/api/v1/tenant/update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setInformation(@RequestBody Map<String, Object> data) {
        try {
            tenantService.updateTenant(data);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            Tenant tenant = tenantService.getTenant(data.get("tenantId").toString());
            String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "更新了租户\"" + tenant.getTenantName() + "\"的信息。";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        } catch (SiemensException e) {
            e.printStackTrace();
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/admin/api/v1/tenant/check", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> checkTenant(String type, String param) {
        Tenant tenant = tenantService.check(type, param);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(tenant).build();
    }

    @RequestMapping(value = "/admin/api/v1/tenant/list/dataTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTenantListByDataTable(HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        Map<String, Object> tenants = new HashMap<>();
        if (dt.isDataTableRequest()) {
            tenants = tenantService.getTenantListByDataTable(request);
        }
//        List<Tenant> tenants = tenantService.getTenantList();

        return tenants;
    }
}
